import 'package:dio/dio.dart' hide LogInterceptor;
import 'package:myapp/components/Logger/loggers.dart';
import 'package:myapp/dio/config/dio_config.dart';
import 'log_interceptor.dart'; // 导入日志拦截器

class DioClient {
  late Dio _dio;

  DioClient([BaseOptions? baseOptions]) {
    _dio = Dio(baseOptions ?? DioConfig.baseOptions);

    _dio.interceptors.add(LogInterceptor()); // 应用拦截器
  }

  Future<dynamic> get(String endpoint) async {
    try {
      Response response = await _dio.get(endpoint);
      return response.data;
    } on DioException catch (e) {
      // 使用DioException处理错误
      String errorMessage;
      if (e.type == DioExceptionType.unknown) {
        errorMessage = 'No Internet connection';
      } else {
        errorMessage = 'Error: ${e.message}';
      }
      logger.e(errorMessage, error: 'GET dio');
      throw Exception(errorMessage);
    }
  }

  Future<dynamic> post(String endpoint, Map<String, dynamic> data) async {
    try {
      Response response = await _dio.post(endpoint, data: data);
      return response.data;
    } on DioException catch (e) {
      // 使用DioException处理错误
      String errorMessage;
      if (e.type == DioExceptionType.unknown) {
        errorMessage = 'No Internet connection';
      } else {
        errorMessage = 'Error: ${e.message}';
      }
      logger.e(errorMessage, error: 'POST dio');
      throw Exception(e.message);
    }
  }
}

DioClient dioClient = DioClient();
